// goods/pages/orderDetails/orderDetails.js
let myRequest = require('../../../common/script/myRequest.js');
let api = require('../../../common/script/api.js');
let utils = require('../../../utils/util');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataCenter: null,
    reasons: [
      '订单不能按预计时间送达',
      '操作有误（商品、地址等选错）',
      '重复下单/误下单',
      '其他渠道价格更低',
      '该商品降价了',
      '不想买了'
    ],
    showModal: false,
    concent_list: ['微信支付', '会员卡支付'],
    curIndex: 0,
    money: '',
    sn: ''
  },
  // 获取数据
  getData() {
    const that = this;
    let data = {
      order_id_sn: that.data.id + '=' + that.data.sn,
      store_id: that.data.storeid,
    }
    wx.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.getOrderDetail, data).then(res => {
      wx.hideLoading();
      if (res.data.status == 1) {
        that.setData({
          dataCenter: res.data.result
        })
      }
    })
  },
  // 去申请售后
  toAfterSale(e) {
    let order_id = e.currentTarget.dataset.order_id;
    wx.navigateTo({
      url: `/goods/pages/afterSales/afterSales?order_id=${order_id}&type=2`
    })
  },
  //确认收货
  orderConfirm(e) {
    const that = this;
    let order_id = e.currentTarget.dataset.order_id;
    let data = {
      order_id: order_id
    }
    wx.showModal({
      content: '是否确认收货',
      confirmText: '确定',
      confirmColor: '#ff5151',
      success(e) {
        if (e.confirm) {
          wx.showLoading({
            title: '加载中...',
          })
          myRequest.EasyHttp.post(api.reqUrls.orderConfirm, data).then(res => {
            wx.hideLoading();
            if (res.data.status == 1) {
              wx.showToast({
                title: res.data.msg,
                icon: 'success',
                duration: 2000
              })
              setTimeout(() => {
                that.getData();
              }, 2000)
              let pages = getCurrentPages(); //获取小程序页面栈
              let beforePage = pages[pages.length - 2]; //获取上个页面的实例对象
              beforePage.getData(); //触发上个页面自定义的shuaxin方法

            } else {
              wx.showModal({
                content: res.data.msg,
                showCancel: false,
                confirmText: '我知道了',
                confirmColor: '#ff5151',
                success(e) {
                  if (e.confirm) {

                  }
                }
              })
            }
          })
        }
      }
    })
  },
  // 查看物流
  toLogistics(e) {
    let order_id = e.currentTarget.dataset.order_id;
    wx.navigateTo({
      url: `/goods/pages/logistics/logistics?order_id=${order_id}`,
    })
  },
  // 隐藏模态对话框
  hideModal() {
    const that = this;
    that.setData({
      showModal: false
    });
  },
  // 显示模态对话框
  showModel(e) {
    const that = this;
    let money = e.currentTarget.dataset.money;
    let sn = e.currentTarget.dataset.sn;
    let memberData = wx.getStorageSync('memberData')
    if (memberData) {
      that.setData({
        curIndex: 0,
        showModal: true,
        money,
        sn
      });
    } else {
      that.setData({
        money,
        sn
      });
      that.debounces()
    }
  },
  // 选择模态框
  choose(e) {
    var index = e.currentTarget.dataset.index
    this.setData({
      curIndex: index
    })
  },
  debounces: utils.throttle(function () {
    this.setData({
      showModal: false
    });
    this.onConfirm()
  }, 5000),
  onConfirm(e) {
    const that = this
    let amountData = {
      trade_type: "JSAPI",
      master_order_sn: that.data.sn,
      account: that.data.money
    }
    wx.showLoading({
      title: '加载中...',
    })
    // curIndex==0 是微信支付，curIndex==1是会员卡支付
    let curIndex = that.data.curIndex
    if (curIndex == 0) {
      myRequest.EasyHttp.post(api.reqUrls.doPay, amountData).then(prop => {
        wx.hideLoading();
        if (prop.data.status == 1) {
          if (prop.data.result.banping == 1) {
            let preOrderId = prop.data.result.wx.pre_order
            let merchantId = prop.data.result.wx.merchant_id
            let opAppId = 'wx38a3350891b22014'
            wx.openEmbeddedMiniProgram({
              appId: opAppId, // 你要打开的小程序appid
              extraData: { //给B小程序传的参数
                autoPay: 1,
              },
              path: `pages/plugin/pay?preOrderId=${preOrderId}&merchantId=${merchantId}`, // 打开的页面路径，如果为空则打开首页
              envVersion: 'release', // 要打开的小程序版本 develop 开发版 trial 体验版 release 正式版
              success(resData) {
                console.log(resData, 11111)
                // 打开成功

                var listener = (props) => {
                  console.log(props, 111)
                  console.log(props.referrerInfo, 222)
                  console.log(props.referrerInfo.extraData, 333)
                  if (!props.referrerInfo.hasOwnProperty('extraData')) {
                    console.log('错误')
                    wx.showModal({
                      content: '付款失败',
                      showCancel: false,
                      confirmText: '我知道了',
                      confirmColor: '#ff5151',
                      success(e) {
                        if (e.confirm) {

                        }
                      }
                    })
                    if (listener) {
                      wx.offAppShow(listener)
                    }
                  }
                  if (props.referrerInfo.extraData.payStatus === '0') {
                    console.log('支付失败')
                    //支付失败
                    //.....
                    wx.showModal({
                      content: '付款失败',
                      showCancel: false,
                      confirmText: '我知道了',
                      confirmColor: '#ff5151',
                      success(e) {
                        if (e.confirm) {

                        }
                      }
                    })
                  }
                  if (props.referrerInfo.extraData.payStatus === '1') {
                    console.log('支付成功')
                    //支付成功
                    //.....

                    setTimeout(() => {
                      wx.navigateTo({
                        url: `/goods/pages/submitOrderSuccess/submitOrderSuccess?orderSn=${that.data.sn}&type=2`
                      })
                    }, 500)
                  }
                  if (props.referrerInfo.extraData.payStatus === '3') {
                    console.log('用户取消支付')
                    //用户取消支付(订单状态流转为已关闭)
                    //......
                    wx.showModal({
                      content: '付款失败',
                      showCancel: false,
                      confirmText: '我知道了',
                      confirmColor: '#ff5151',
                      success(e) {

                      }
                    })
                  }
                  if (listener) {
                    wx.offAppShow(listener)
                  }
                };
                wx.onAppShow(listener)
              },
              fail(e) {
                console.log(e, 999999)
                // 打开失败
              },
            })
          } else {
            wx.requestPayment({ // 调取支付
              timeStamp: prop.data.result.timeStamp.toString(),
              nonceStr: prop.data.result.nonceStr,
              package: prop.data.result.package,
              signType: prop.data.result.signType,
              paySign: prop.data.result.sign,
              success(res) {
                if (res.errMsg == "requestPayment:ok") {
                  wx.showToast({
                    title: '付款成功',
                    icon: 'success',
                    duration: 2000
                  })
                  let pages = getCurrentPages(); //获取小程序页面栈
                  let beforePage = pages[pages.length - 2]; //获取上个页面的实例对象
                  beforePage.getData(); //触发上个页面自定义的shuaxin方法
                  wx.navigateTo({
                    url: `/goods/pages/submitOrderSuccess/submitOrderSuccess?orderSn=${that.data.sn}&type=2`
                  })
                } else {
                  wx.showModal({
                    content: '付款失败',
                    showCancel: false,
                    confirmText: '我知道了',
                    confirmColor: '#ff5151',
                    success(e) {
                      if (e.confirm) {

                      }
                    }
                  })
                }
              },
              fail(res) {
                wx.showModal({
                  content: '付款失败',
                  showCancel: false,
                  confirmText: '我知道了',
                  confirmColor: '#ff5151',
                  success(e) {
                    if (e.confirm) {

                    }
                  }
                })
              }
            })
          }

        }
      })
    } else {
      myRequest.EasyHttp.post(api.reqUrls.membercardDopay, amountData).then(prop => {
        wx.hideLoading();
        if (prop.data.status == 1) {
          wx.showToast({
            title: "付款成功",
            icon: 'success',
            duration: 2000
          })
          let pages = getCurrentPages(); //获取小程序页面栈
          let beforePage = pages[pages.length - 2]; //获取上个页面的实例对象
          beforePage.getData(); //触发上个页面自定义的shuaxin方法
          wx.navigateTo({
            url: `/goods/pages/submitOrderSuccess/submitOrderSuccess?orderSn=${that.data.sn}&type=2`
          })
        } else if (prop.data.status == -1002) {
          // wx.showModal({
          //   content: '会员卡余额不足，是否去充值？',
          //   confirmText: '去充值',
          //   success(e) {
          //     if (e.confirm) {
          //       wx.navigateTo({
          //         url: `/package/pages/recharge/recharge`,
          //       })
          //     }
          //   }
          // })
          wx.showModal({
            content: prop.data.msg,
            showCancel: false,
            confirmText: '我知道了',
            confirmColor: '#ff5151',
            success(e) {
              if (e.confirm) {}
            }
          })
        } else {
          wx.showModal({
            content: prop.data.msg,
            showCancel: false,
            confirmText: '我知道了',
            confirmColor: '#ff5151',
            success(e) {
              if (e.confirm) {}
            }
          })
        }
      })
    }
  },
  // 取消订单
  cancelOrder(prop) {
    const that = this;
    wx.showModal({
      content: '是否取消该订单',
      confirmText: '确定',
      confirmColor: '#ff5151',
      success(e) {
        if (e.confirm) {
          let order_id = that.data.dataCenter.order_id;
          let master_order_sn = that.data.dataCenter.master_order_sn;
          let order_status_detail = that.data.dataCenter.order_status_detail;
          if (order_status_detail == "待支付") {
            let data = {
              order_id_sn: order_id + '=' + master_order_sn
            }
            wx.showLoading({
              title: '加载中...',
            })
            myRequest.EasyHttp.post(api.reqUrls.cancelOrder, data).then(res => {
              wx.hideLoading();
              if (res.data.status == 1) {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'success',
                  duration: 2000
                })
                setTimeout(() => {
                  that.getData();
                }, 2000)
                let pages = getCurrentPages(); //获取小程序页面栈
                let beforePage = pages[pages.length - 2]; //获取上个页面的实例对象
                beforePage.getData(); //触发上个页面自定义的shuaxin方法
              } else {
                wx.showModal({
                  content: res.data.msg,
                  showCancel: false,
                  confirmText: '确定',
                  confirmColor: '#ff5151',
                  success(e) {
                    if (e.confirm) {}
                  }
                })
              }
            }).catch(err => {
              wx.showModal({
                content: err.toString(),
                showCancel: false,
                confirmText: '确定',
                confirmColor: '#ff5151',
                success(e) {
                  if (e.confirm) {}
                }
              })
            })
          } else {
            wx.showActionSheet({
              itemList: that.data.reasons,
              success(res) {
                let data = {
                  order_id: order_id,
                  consignee: that.data.dataCenter.consignee,
                  mobile: that.data.dataCenter.mobile,
                  user_note: that.data.reasons[res.tapIndex],
                  is_json: 1
                }
                wx.showLoading({
                  title: '加载中...',
                })
                myRequest.EasyHttp.post(api.reqUrls.cancelPaidOrder, data).then(res => {
                  wx.hideLoading();
                  if (res.data.status == 1) {
                    wx.showToast({
                      title: res.data.msg,
                      icon: 'success',
                      duration: 2000
                    })
                    setTimeout(() => {
                      that.getData();
                    }, 2000)
                    let pages = getCurrentPages(); //获取小程序页面栈
                    let beforePage = pages[pages.length - 2]; //获取上个页面的实例对象
                    beforePage.getData(); //触发上个页面自定义的shuaxin方法
                  } else {
                    wx.showModal({
                      content: res.data.msg,
                      showCancel: false,
                      confirmText: '确定',
                      confirmColor: '#ff5151',
                      success(e) {
                        if (e.confirm) {}
                      }
                    })
                  }
                }).catch(err => {
                  wx.showModal({
                    content: err.toString(),
                    showCancel: false,
                    confirmText: '确定',
                    confirmColor: '#ff5151',
                    success(e) {
                      if (e.confirm) {}
                    }
                  })
                })
              },
              fail(res) {
                console.log(res.errMsg)
              }
            })
          }

        }
      }
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this;
    that.setData({
      id: options.id,
      sn: options.sn,
      storeid: options.store_id,
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const that = this;
    that.getData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage() {

  // }
})